/*
 * @Descripttion: api
 * @Author: zzt
 * @Date: 2021-08-18 13:12:41
 * @LastEditors: zzt
 * @LastEditTime: 2021-09-29 11:30:18
 */
import http from 'axios'
import {baseUrl} from './baseUrl'
import store from '../store'
import {toast} from '../utils/toast'
import router from '../router';
//导入axios
var base_url = baseUrl.getBaseUrl();
console.log(`当前环境是：${process.env.NODE_ENV} ${base_url}`);

var axios = http.create({
    baseUrl: base_url,
    // headers: {
    //     'Content-Type': 'application/json;charset=UTF-8',
    //     'X-REQUESTED-WITH': 'xmlhttprequest',
    //     'Request-App': 'web',
    //     'lang': 'zh_CN'
    // },
    transformRequest: [function (data) {
        // 这里可以在发送请求之前对请求数据做处理，比如form-data格式化等，这里可以使用开头引入的Qs（这个模块在安装axios的时候就已经安装了，不需要另外安装）
        var token = store.getters.token
		if (token !== null && token !== "" && typeof (token) !== "undefined") {
			data['token'] = token;
		}
        return JSON.stringify(data);
    }]
});
export const ajax = function (action, data, async, type, successfn, isLoading, errorFun) {
    var url = action;
    async = (async ==null || async =="" || typeof (async) == "undefined") ? true : async;
    type = (type == null || type == "" || typeof (type) == "undefined") ? "post" : type;
    data = (data == null || data == "" || typeof (data) == "undefined") ? {
        "date": new Date().getTime()
    } : data;

    //使用get 方法的时候将参数拼入url中
    if (type == 'get') {
        for (let i in data) {
            if (url.indexOf("?") != -1) {
                url += '&' + i + '=' + data[i]
            } else {
                url += '?' + i + '=' + data[i]
            }

        }
    };
    // 发送 ajax 请求
    axios({
            method: (type == null || type == "" || typeof (type) == "undefined") ? "post" : type, // default,
            url: base_url + url,
            data: data,
            timeout: 10000,
        }).then(function (info) {
			var res = info.data;
			//登录失效
			if (res.code == '401' || res.code == '403'|| res.code == '500'|| res.code == '0') {
                store.dispatch('setToken', '');
                router.push({
                    name: "login"
                });
                return false;
			}
            successfn(res);
        })
        .catch(function (e) {
            successfn({
                code: '500',
                message: e,
            });
            window.console.log(e);
        });
};
//请求超时
function timeOut() {
    // Toast("Time out");
}